﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f; // 角色移动速度
    public float jumpForce = 5f; // 跳跃高度
    private Rigidbody2D rb;
    private Animator animator;
    private Vector3 originalScale; // 保存原始缩放比例
    private BoxCollider2D mf;
    private bool isGround;
    public Mainmenu mainMenu; // 指向主菜单脚本的引用

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        mf = GetComponent<BoxCollider2D>();
        animator = GetComponent<Animator>();
        originalScale = transform.localScale;
        Debug.Log("Original Scale: " + originalScale.ToString());
    }

    void Update()
    {
        walk();
        jump();
        CheckGrounded();
        SwitchAnimation();
        InteractWithObjects();
    }

    void CheckGrounded()
    {
        isGround = mf.IsTouchingLayers(LayerMask.GetMask("Ground"));
    }

    void walk()
    {
        float moveDir = Input.GetAxis("Horizontal");
        Vector2 playerVel = new Vector2(moveDir * moveSpeed, rb.velocity.y);
        rb.velocity = playerVel;
        bool playerHasXAxisSpeed = Mathf.Abs(rb.velocity.x) > Mathf.Epsilon;
        animator.SetBool("walk", playerHasXAxisSpeed);
        // 翻转角色
        if (moveDir > 0)
        {
            transform.localScale = originalScale; // 向右移动时不翻转
        }
        else if (moveDir < 0)
        {
            transform.localScale = new Vector3(-originalScale.x, originalScale.y, originalScale.z); // 向左移动时翻转
        }
    }

    void jump()
    {
        if (Input.GetButtonDown("Jump"))
        {
            if (isGround)
            {
                animator.SetBool("jump", true);
                Vector2 jumpVel = new Vector2(0.0f, jumpForce);
                rb.velocity = Vector2.up * jumpVel;
            }
        }
    }

    void SwitchAnimation()
    {
        animator.SetBool("Idle", false);
        if (animator.GetBool("jump"))
        {
            if (rb.velocity.y < 0.0f)
            {
                animator.SetBool("jump", false);
                animator.SetBool("fall", true);
            }
        }
        else if (isGround)
        {
            animator.SetBool("fall", false);
            animator.SetBool("Idle", true);
        }
    }

    void InteractWithObjects()
    {
        // 检查玩家是否按下了E键
        if (Input.GetKeyDown(KeyCode.E))
        {
            mainMenu.Loadlevel(SceneManager.GetActiveScene().buildIndex + 1);
        }
    }
}
